<?php
/**
 * Application main class
 * @author Kirill A Egorov kirill.a.egorov@gmail.com 
 * @copyright Copyright (C) 2011-2012  Kirill A Egorov, 
 * DVelum project http://code.google.com/p/dvelum/ , http://dvelum.net
 * @license General Public License version 3
 */
class Application{
    
    static protected $_storage;
    static protected $_mainConfig;      
    static protected $_systemCache = false;
    static protected $_dataCache = false;
    static protected $_templates = '';
    /**
     * Database connection
     * @property Zend_Db_Adapter_Abstract
     */
    static protected $_db;
    
    public  function __construct()
    {
        self::$_storage = Store::factory(Store::Local);
        self::$_mainConfig = self::$_storage->get('config_main');
        /**
         * Apply configs
         */
        Filter::setDelimetr(self::$_mainConfig['urlDelimetr']);
        Request::setDelimetr(self::$_mainConfig['urlDelimetr']);
        Request::setExtension(self::$_mainConfig['urlExtension']);
        Resource::setCachePaths(self::$_mainConfig['jsCacheSysUrl'] , self::$_mainConfig['jsCacheSysPath']);
        Resource::setDocRoot(self::$_mainConfig['docroot']);

        if(self::$_dataCache)
        	Resource::setCache(self::$_dataCache);
    }
    /**
     * Set System cache frontend
     * @param Zend_Cache_Core $cache
     */
    static public function setSystemCache(Zend_Cache_Core $cache)
    {
        self::$_systemCache = $cache;
    }
    /**
     * Set Data cache Frontend
     * @param Zend_Cache_Core $cache
     */
    static public function setDataCache(Zend_Cache_Core $cache)
    {
        self::$_dataCache = $cache;
    } 
    /**
     * Get Data cache frontend
     * @return Zend_Cache_Core or false
     */
    static public function getDataCache()
    {
    	return self::$_dataCache;
    }
    /**
     * Get System cache frontend
     * @return Zend_Cache_Core
     */
    static public function systemCache()
    {
        return self::$_systemCache;
    }
    /**
     * Get Data cache frontend
     * @return Zend_Cache_Core
     */
    static public function dataCache()
    {
        return self::$_dataCache;
    }
    /**
     * Get database connection handler
     * @return Zend_Db_Adapter_Abstract
     */
    static public function getDbConnection()
    {
    	return self::$_db;
    }
    /**
     * Run application
     */
    public function run()
    {
        header('Content-Type: text/html; charset=utf-8');
        date_default_timezone_set(self::$_mainConfig['timezone']);
        /**
         * Init lang dictionary
         */ 
        Lang::setDictionary(Config::factory(Config::File_Array, self::$_mainConfig['docroot'] . '/system/lang/' . self::$_mainConfig['language'] . '.php'));   
        /**
         * Database connection
         */
        if(self::$_mainConfig['development'])
        	$file = self::$_mainConfig['configs'].'db_dev.php';
        else 
        	$file = self::$_mainConfig['configs'].'db.php';
        
        $dbConfig = Config::factory(Config::File_Array, $file);    
          
        $db = Zend_Db::factory('Mysqli' , $dbConfig->__toArray());
          
        /*
         * Enable Db profiler for development mode
         * Attention! Db Profiler causes memory leaks at background tasks. (Dev mode)
         */
        if(self::$_mainConfig['development']){
        	$db->getProfiler()->setEnabled(true);
            Debug::setDbProfiler($db->getProfiler()); 
        }
        /*
         * Store connection config in local storage
         */
        self::$_storage->set('db' , $db);
        self::$_storage->set('dbConfig', $dbConfig);
        
        self::$_db = $db;
        
        Db_Object::setConfigPath(self::$_mainConfig['object_configs']);
        Db_Object::setDbConnection($db);
        Db_Object::setDbPrefix($dbConfig['prefix']);
        Db_Object_Store::setEventManager(Eventmanager::getInstance());
        Db_Object::setLinksObject(self::$_mainConfig['orm_links_object']);
        
        /*
         * Initialize templates cache
         */
        if(self::$_dataCache!==false)
            Template::setCache(self::$_dataCache);
 
        $page = Request::getInstance()->getPath(0);
        
        if($page === self::$_mainConfig['adminPath'])
            $this->_runBackend();
        else 
            $this->_runFrontend();             
    }
    /**
     * Run backend application
     */
    protected function _runBackend()
    {
        /*
         * Get backend configuration
         */
        $backendConfig = Config::factory(Config::File_Array, self::$_mainConfig['configs'] . 'backend.php');
        
        self::$_storage->set('config_backend' , $backendConfig);    
        self::$_templates = self::$_mainConfig->get('templates').'system/'.$backendConfig->get('theme') . '/';
        
        /*
         * Chek if session id has been passed
         * It used by Uploadify component of Media Library
         */
        if(isset($_REQUEST['sid']))
            session_id($_REQUEST['sid']);
        /*
         * Start routing
         */
        Backend_Router::getInstance()->route();
        /*
         * Define frontent JS variables
         */
        $res = Resource::getInstance();
        $res->addInlineJs('
        	app.admin = "/'.self::$_mainConfig['adminPath'].'";
        	app.delimeter = "'.self::$_mainConfig['urlDelimetr'].'";
        	app.root = "/'.self::$_mainConfig['adminPath'].self::$_mainConfig['urlDelimetr'].Request::getInstance()->getPath(1).self::$_mainConfig['urlDelimetr'].'";
        ');
        
        $user = User_Admin::getInstance();
        /*
         * Update "Users Online" statistics
         */
        Model_Online::getInstance()->addOnline(session_id(),$user->id);
        /*
         * Load template
         */
        $template = new Template();
        $template->disableCache();
        $template->page = Page::getInstance();
        $template->urlPath = Request::getInstance()->getPath(1);
        $template->resource = $res;
        $template->path = self::$_templates;
        $template->adminPath =  self::$_mainConfig['adminPath'];
        $template->development =  self::$_mainConfig['development'];
        $template->version = self::$_mainConfig['version'];
        $template->lang = self::$_mainConfig['language'];
        $template->modules = Config::factory(Config::File_Array, self::$_mainConfig['backend_modules']);
        $template->userModules = $user->getAvailableModules();
        Response::put($template->render(self::$_templates . 'layout.php'));
    }
    
    /**
     * Run frontend application
     */
    protected function _runFrontend()
    {       
    	$user = User::getInstance();
    	/*
         * Update "Users Online" statistics
         */
        Model_Online::getInstance()->addOnline(session_id(),$user->id);
        
        self::$_templates = self::$_mainConfig->get('templates').'public/';   	 	
        /*
         * Start routing
         */
        Frontend_Router::getInstance()->route();
    }
    /**
     * Terminate application
     */
    static public function close()
    {
        exit();
    }
    /**
     * Get templates path
     * @return string
     */
    static public function  getTemplatesPath()
    {
        return self::$_templates;
    }
    /**
     * Get application config
     * @return Config_Abstract
     */
    static public function getConfig($config = 'main')
    {
    	switch ($config){
    		case 'main': return self::$_mainConfig;
    			break;
    	}
    } 
    /**
     * Get local object storage
     * @return Store_Local
     */
    static public function getStorage(){
    	return self::$_storage;
    } 
}